/**
 * 分页显示数据表格，具有分页显示数据、排序、设置分页大小功能
 */
Ext.namespace("Ext.ux.grid");

Ext.ux.grid.czGrid = Ext.extend(Ext.grid.GridPanel, {

	// 表格结构
	structure: null,
	enableRefreshBtn: true,	//刷新按钮
	// 关键字段
	keyField: null,
	keyFieldIndex: -1,
	browseUrl: '',				//浏览地址URL
	saveBtn: true,	//新增
	editButton: true,	//修改
	delButton: true,	//删除
    collapsible : true,
    animCollapse : true,
    allowDomMove : true,
    iconScale: 'medium',
    
	// 获取数据的URL
	url: '',
	
	// 默认排序字段
	defaultSortField: '',
	defaultSortDir: 'DESC',
	
	// 预加载数据
	preload: true,
	
	// 是否需要分页工具栏，默认为true
	needPage: true,
	
	// 是否显示分页信息
	showPageInfo: true,
	
	// 每页记录数
	pageSize: 10,
	
	// 是否显示加载提示
	loadMask: true,
	
	// 是否显示边框
	frame: false,

	stripeRows: true,
	columnLines: true,
	
	groupByCombo: null,

	view: new Ext.grid.GroupingView({
		forceFit: true,
		groupTextTpl: '{text} ({[values.rs.length]} {["项"]})'
	}),
  
	// 组件初始化
	initComponent: function(){
		if(this.structure != null){
			this.initStructure();	// 根据表格结构构造ColumnModel对象和Record对象
		}
		Ext.ux.grid.czGrid.superclass.initComponent.call(this);
	},

	// 根据表格结构构造ColumnModel对象、Record对象、Store对象等
	initStructure: function(){
		this.tbar = new Ext.Toolbar();
		this.tbar.addItem('-');
		if(this.saveBtn){
			this.tbar.addItem({
				text: '新增',
				iconCls: 'icon-save',
				scale: this.iconScale,
				handler: function(){
					this.toSavePerson();
				},
				scope: this
			});
			this.tbar.addItem('-');
			
		}
		if(this.editButton){
		// var sqb = parent.document.getElementById('shljcz_formIframe').contentWindow;
			this.tbar.addItem({
				text: '修改',
				iconCls: 'icon-edit',
				scale: this.iconScale,
				handler: function(){
					this.editPerson();
				},
				scope: this
			});
			this.tbar.addItem('-');
		
			this.on('rowdblclick', function(grid){
				this.viewPerson();
			}, this);
		}
		
		if(this.delButton){
			this.tbar.addItem({
				text: '删除',
				iconCls: 'icon-delete',
				scale: this.iconScale,
				handler: function(){
					this.deletePerson();
				},
				scope: this
			});
			this.tbar.addItem('-');
			
		
		}
		
		if(this.enableRefreshBtn){
			this.tbar.addItem({
				iconCls: 'icon-refresh',
				text: '刷新',
				
				handler: function(){
					this.store.reload();
				},
				scope: this
			});
			this.tbar.addItem('-');
		}
		this.sm = new Ext.grid.RowSelectionModel({singleSelect:false});

		var groupByComboData = new Array();

		var oColModel = new Array();
		var oRecord = new Array();

		oColModel[0] = new Ext.grid.RowNumberer();

		// 构造GRID所需对象
		for(var i=0, len=this.structure.length; i<len; i++){

			// 表格结构的列定义
			var column = this.structure[i];

			// 如果字段为hidden，则不生成columnMode
			//if (column.hidden == undefined || !column.hidden){
				
				if(column.isGroupField){
					var groupByComboItem = [column.name, column.header];
					groupByComboData[groupByComboData.length] = groupByComboItem;
				}
				
				oColModel[oColModel.length] = {
					header: column.header,
					dataIndex: column.name,
					hidden: column.hidden == null ? false : column.hidden,
					width: column.width == null ? 80 : column.width,
					sortable: column.sortable
				};
				oColModel[oColModel.length-1].renderer = Ext.grid.ColumnModel.defaultRenderer;
			//}

			oRecord[oRecord.length] = {
				name: column.name
			};
		}
		
		
		// 构造columnModel
		this.cm = new Ext.grid.ColumnModel(oColModel);
		this.colModel = this.cm;
	
		// 默认可排序
		this.cm.defaultSortable = true;

		// 构造记录对象和reader对象
		var record = Ext.data.Record.create(oRecord);
		var reader;
		
		if(this.keyField != null){
			reader = new Ext.data.JsonReader({
				totalProperty: 'totalCount',
				root: 'result',
				id: this.keyField
			}, record);
		}
		else if(this.keyFieldIndex >= 0){
			reader = new Ext.data.ArrayReader({
				totalProperty: 'totalCount',
				root: 'result',
				idIndex: this.keyFieldIndex
			}, record);
		}
		
		// 构造store对象
		this.ds = new Ext.data.GroupingStore({
			proxy: new Ext.data.HttpProxy({
				url: ctx + this.url
			}),
			reader: reader,
			sortInfo: {
				field: this.defaultSortField,
				direction: this.defaultSortDir
			},
			groupField: null,
			remoteGroup: true,
			remoteSort: true
		});
		this.store = this.ds;
		
		// 添加分页工具栏  
		if (this.needPage){
			var pagingToolbar = new Ext.PagingToolbar({
				store: this.ds,
				pageSize: this.pageSize,
				displayInfo: this.showPageInfo,
				displayMsg: '第 {0} - {1} 条记录 / &nbsp;共 {2} 条记录',
				emptyMsg: '<font color="red">提示：没有任何符合条件的记录！</font>'
			});
			this.bbar = pagingToolbar;
			this.bottomToolbar = this.bbar;
		}

		// 加载数据列表
		if(this.preload)
			this.store.load({params:{start:0, limit:this.pageSize}});

		this.tbar.addItem('->');
		this.tbar.addItem('-')
		this.tbar.addItem(' ');


		var groupByComboStore = new Ext.data.ArrayStore({
	        fields: ['name', 'header'],
	        data: groupByComboData
	    });
		
		
		this.tbar.addItem('-');
	},
viewPerson:function(){
	var sel = this.getSelectionModel().getSelections();
	if(sel.length == 0) {
      Ext.Msg.alert('系统提示', '你没有选中任何记录，请重新选择！');
      return;
    }
     var personId=sel[0].get('personId');
     var url=ctx+"/csshlj-cz-person!getPerson.action?personId="+personId;

      	  Ext.Ajax.request({
	       url: url,
	       success:function(result){
	       		window.toviewPerson(result);
	       },
	       failure:function(){
	       	 Ext.MessageBox.alert('信息', "系统繁忙，请稍后重试");
	       },
	       params: {
	            personId:personId
	       }
        });
     
     //window.viewPerson(url);
},
editPerson:function(){
	 var sel = this.getSelectionModel().getSelections();
	if(sel.length == 0) {
      Ext.Msg.alert('系统提示', '你没有选中任何记录，请重新选择！'); return;
    }
 	 var personId=sel[0].get('personId');
 	 if(personId==""){
 	   Ext.MessageBox.alert('信息', "请选择单条记录");
 	 }
 	 var url=ctx+"/csshlj-cz-person!getPerson.action";
 	  Ext.Ajax.request({
	       url: url,
	       success:this.toUpdatePerson,
	       failure:function(){
	       	 Ext.MessageBox.alert('信息', "系统繁忙，请稍后重试");
	       },
	       params: {
	            personId:personId
	       }
        });
 },
 
 toUpdatePerson:function(result){
 	var array = Ext.decode(result.responseText);
 	var win=new Ext.Window({
        title:'编辑专业技术人员',
        width:450,
        autoHeight:true,    
        modal: true,
        labelAlign:'right',
        buttonAlign:'center',
        closeAction:'close',
        html:'<table width="600" border="0" cellspacing="2" cellpadding="2">'+
        '<tr><td colspan="2"><input type="hidden" name="personId" id="personId" value="'+array.personId+'"></td>'+
         '<tr><td colspan="2"><input type="hidden" name="czid" id="czid" value="'+array.czid+'"></td>'+
        '<tr><td width:200 align=right>姓名:</td><td><input type="text" name="name" size="25" id="name" value="'+array.name+'"></td>'+
        '<tr><td width:200 align=right>学历:</td><td><input type="text" name="xl"  size="25" id="xl" value="'+array.xl+'"></td>'+
        '<tr><td width:200 align=right>专业:</td><td><input type="text" name="zy" id="zy" size="25" value="'+array.zy+'"></td>'+
        '<tr><td width:200 align=right>简历附件:</td><td><input type="file" name="jlfile"  size="25" id="jlfile"></td>'+
        '<tr><td width:200 align=right>学历附件:</td><td><input type="file" name="xlfile"  size="25" id="xlfile"></td>'+
        '</table>',
        buttons:[{text:'保 存',handler:function(){
        	var xlfile = dwr.util.getValue('xlfile');
			var jlfile =dwr.util.getValue('jlfile');
			var name = Ext.get('name').dom.value;
			var czid = Ext.get('czid').dom.value;
			var personId = Ext.get('personId').dom.value;
			var xl = Ext.get('xl').dom.value;
			var zy = Ext.get('zy').dom.value;
			var xlfileName="";
			var jlfileName="";
			if(xlfile!=null){
			    xlfileName = xlfile.value.substring(xlfile.value.lastIndexOf(".") + 1, xlfile.value.length);
			}
			if(jlfile!=null){
			    jlfileName = jlfile.value.substring(jlfile.value.lastIndexOf(".") + 1, jlfile.value.length);
			}
			var obj ={
				  personId:personId,
				  czid:czid,
				  xlfileName:xlfileName,
				  jlfileName:jlfileName,
				  name:name,
				  xl:xl,
				  zy:zy
			};
		    var params=Ext.encode(obj);
			CsshljCntl.updateShljPerson(params,jlfile,xlfile, function (result){
				var jsonData =eval('('+result+')');
				var resultError="";
				for(var key in jsonData){
					resultError=jsonData[key];
				}
				if(resultError==true){
					Ext.Msg.alert('系统提示', '修改成功！');
					win.close();
					window.reloadPerson();
				}
			});
        }
        },{text:'取 消',handler:function(){
            win.close();
        }}]
    }).show();

 },
 toSavePerson:function(){
 	var czid=document.getElementById("id").value;
 	if(czid==""){
 		Ext.Msg.alert('系统提示', '请先保存基本信息！');
 		return;
 	}
 var url=ctx+"/csshlj-cz-person!saveOrUpdatePerson.action?czid="+czid;
 var personForm=new Ext.form.FormPanel({
 	  id:"zyryForm",     
      height:400,   
      width:650, 
      labelWidth:80,   
      labelAlign:"left",   
      frame:true,   
      url: url,
	  method: 'POST ',  
      fileUpload:true,   
      defaults:{xtype:"field",width:350},   
      items:[{   
              xtype:"textfield", 
              id:"name",  
              name:"name",   
              fieldLabel:"姓名",   
              allowDecimals:false,   
              allowBlank:false,   
              blankText:"姓名不能为空"  
             },{   
              xtype: 'textfield',
     		  name: 'personId',
     		  hidden: true
             },{   
              xtype:"textfield",   
              id:"xl",
              name:"xl",   
              fieldLabel:"学历"  
             },{   
              xtype:"textfield",   
              id:"zy",
              name:"zy",   
              fieldLabel:"专业"  
             },{   
             id: 'xlfile',   
             name:'xlfile',   
             fieldLabel:"学历附件",   
             inputType:"file"  
             },{   
             id: 'jlfile',   
             name:'jlfile',   
             fieldLabel:"简历附件",   
             inputType:"file"  
             }] 
    });
		var win = new Ext.Window({
			title: '新增专业技术人员',
			modal: true,
			width: 500,
			height: 250,   
	        modal: true,
	        buttonAlign:'center',
	        closeAction:'close',
	        items : personForm,
			buttons:[{text:'保 存',handler:function(){
			personForm.getForm().submit({
				success: function(form, action){
				   if(action.result.msg=="true"){
					    Ext.MessageBox.alert('信息', "数据提交成功");
						win.close();
						window.reloadPerson();
					}
				}
			});
			store.reload();
			}},{text:'取 消',handler:function(){
            win.close();
        }}]
		});
		win.show();
},
deletePerson:function(){
		var sel = this.getSelectionModel().getSelections();
	    Ext.MessageBox.confirm('警告!','您确定要删除吗?',function(btn){
        if (btn == 'yes'){
			if(sel.length == 0) {
		      Ext.Msg.alert('系统提示', '你没有选中任何记录，请重新选择！'); return;
		    }
			var personId=sel[0].get('personId');
			var url=ctx+"/csshlj-cz-person!delPerson.action";
			Ext.Ajax.request({
		       url: url,
		       success:function(response){
		         var result=response.responseText;
		         if(result=="true"){
		            Ext.MessageBox.alert('系统提示', "删除成功");
		            window.reloadPerson();
		         }
		       },
		       failure:function(){
		       	 Ext.MessageBox.alert('信息', "系统繁忙，请稍后重试");
		       },
		       params: {
		            personId:personId
		       }
	        });
        }
    });
	
},
savePerson: function(){
var czid=document.getElementById("id").value;
var url=ctx+"/csshlj-cz-person!saveOrUpdatePerson.action";
var name = Ext.get('name').dom.value;
var xl = Ext.get('xl').dom.value;
var zy = Ext.get('zy').dom.value;
var xlfile = Ext.get('xlfilepath').dom.value;
var jlfile = Ext.get('jlfilepath').dom.value;
 if(name==""){
  	Ext.Msg.alert('系统提示', '姓名不能为空！');
 		return;
  }

 
  
/*personForm.form.submit({
	url: url,
	waitMsg : '正在保存数据，请稍候...'
});*/


var obj ={
  czid:czid,
  name:name,
  xl:xl,
  zy:zy
  };
  var params=Ext.encode(obj);
  alert(params);
  CsshljczCntl.saveOrUpdatePerson(params, xlfile,jlfile, function (result){
	alert(result);
});
  
  
/*Ext.Ajax.request({
	url: url,
	dataType: 'json',
	params:params,
	success:function(response){
		
	},
	failure:function(){
	},
	scope: this
});*/
  
},
	//浏览更多
	browse: function(){
		parent.window.location = ctx + this.browseUrl;
	}
});

